package model;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 
 * @author Michael Elgart, tyy
 *
 */
public abstract class FileParser {
    private static final String DATE = "Date";
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    /**
     * empty constuctor.
     */
    public FileParser() { }

    /**
     * Reads from the input scanner and fills the given table.
     * @param input The InputStream to be read from
     * @param table The DataTable to be filled
     */
    public abstract void readInput(InputStream input, DataTable table);

    /**
     * convert the string columns into the correct data type.
     * and add the columns to the data table
     */
    protected void convertColumns (DataTable table, String[] columnNames,
        List<ArrayList<String>> contentStrings) {
        for (int j = 0; j < columnNames.length; j++) {
            //if the column is dates, parse the strings into dates
            if (columnNames[j].equals(DATE)) {
                ArrayList<Date> dateArray = new ArrayList<Date>();
                for (String s : contentStrings.get(j)) {
                    try {
                        dateArray.add(new SimpleDateFormat(DATE_FORMAT).parse(s));
                    }
                    catch (ParseException e) {
                        throw new ModelException("Incorrectly formatted dates", e);
                    }
                }
                table.addColumn(columnNames[j], dateArray);
            }
            //if the column is not dates, assume the contents are numbers
            else {
                ArrayList<Double> numArray = new ArrayList<Double>();
                for (String s : contentStrings.get(j)) {
                    try {
                        numArray.add(Double.parseDouble(s));
                    }
                    catch (NumberFormatException e) {
                        throw new ModelException("Incorrectly formatted numbers", e);
                    }
                }
                table.addColumn(columnNames[j], numArray);
            }
        }
    }
    /**
     * 
     * @param columnNames
     * @return
     */
    protected List<ArrayList<String>> initialize2DArrayList (String[] columnNames) {
        ArrayList<ArrayList<String>> contentStrings = new ArrayList<ArrayList<String>>();
        for (int k = 0; k < columnNames.length; k++) {
            ArrayList<String> emptyContent = new ArrayList<String>();
            contentStrings.add(emptyContent);
        }
        return contentStrings;
    }
}
